# -*- coding: UTF-8 -*-
import threading


def change_it(n):
    # print('change it')
    # 先存后取，结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n


def run_thread(n):
    for i in range(times):
        change_it(n)


def no_lock():
    t1 = threading.Thread(target=run_thread, args=(5,))
    t2 = threading.Thread(target=run_thread, args=(8,))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    print(balance)


# 加锁安全
lock = threading.Lock()


def run_thread_safe(n):
    for i in range(times):
        # 先要获取锁:
        lock.acquire()
        try:
            # 放心地改吧:
            change_it(n)
        finally:
            # 改完了一定要释放锁:
            lock.release()


def with_lock():
    t1 = threading.Thread(target=run_thread_safe, args=(5,))
    t2 = threading.Thread(target=run_thread_safe, args=(8,))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    print(balance)


if __name__ == '__main__':
    # 假定这是你的银行存款:
    balance = 0
    # times = 1000
    times = 10000000
    # no_lock()
    with_lock()
